import { Button, message, Table, Spin, Modal as AntdModal } from 'antd'
import services from '@/services'
import type { ChatFlow } from '@/services/features/chat-flows'
import './Content.module.less'
import Detail from './Detail'
import EditFlow from './EditFlow'

export default function Content() {
  const [flows, setFlows] = useState<ChatFlow[] | null>(null)
  const load = useCallback(async () => {
    const res = await services.features.chatFlows.load()
    if (!res.success) void message.error(`工作流加载失败：${res.error}`)
    else setFlows(res.data)
  }, [])
  useEffect(() => void load(), [load])

  const remove = useCallback(
    async (id: number) => {
      const res = await services.features.chatFlows.remove(id)
      if (res.success) void message.success('工作流删除成功')
      else void message.error(`工作流删除失败：${res.error}`)
      void load()
    },
    [load],
  )

  const confirmRemove = useCallback(
    (flow: ChatFlow) => {
      AntdModal.confirm({
        title: '确认删除此工作流吗？',
        content: <div>
          删除后，所有配置了此工作流的联系人将不再收到后续的工作流消息。相关配置也会一并删除。
        </div>,
        onOk() {
          void remove(flow.id)
        },
      })
    },
    [remove],
  )

  const [editing, setEditing] = useState<ChatFlow | null | false>(false)
  const editFinish = useCallback(() => {
    setEditing(false)
    void load()
  }, [load])

  const [showDetail, setShowDetail] = useState<ChatFlow | null>(null)

  // ===============================================================

  const loading = <div styleName="loading">
    <Spin tip="加载中..." size="large" />
  </div>

  const renderActions = useCallback(
    (flow: ChatFlow) => {
      return <>
        <Button type="link" onClick={() => setEditing(flow)}>
          编辑
        </Button>
        <Button type="link" onClick={() => setShowDetail(flow)}>
          执行详情
        </Button>
        <Button type="link" danger onClick={() => confirmRemove(flow)}>
          删除
        </Button>
      </>
    },
    [confirmRemove],
  )

  return <main>
    <header>
      你可以创建聊天工作流，并且在客户/群聊天侧边栏配置工作流，Quntool
      将按照工作流的内容，自动向客户/群发送聊天消息。为了防止造成骚扰，每个客户/群同时只能配置一个私聊工作流。
    </header>
    <div styleName="actions">
      <Button type="primary" onClick={() => setEditing(null)}>
        新建工作流
      </Button>
    </div>

    {flows === null ? loading : null}

    {flows !== null ? (
      <Table<ChatFlow> rowKey="id" dataSource={flows} scroll={{ y: 500 }} pagination={false}>
        <Table.Column<ChatFlow> title="名称" dataIndex="name" />
        <Table.Column<ChatFlow>
          title="类型"
          render={(_, flow) => (flow.forGroup ? '群聊' : '私聊')}
        />
        <Table.Column<ChatFlow>
          title="操作"
          key="action"
          width={250}
          styleName="flow-actions"
          render={renderActions}
        />
      </Table>
    ) : null}

    <EditFlow flow={editing} onFinish={editFinish} />
    <Detail showing={showDetail} onClose={() => setShowDetail(null)} />
  </main>
}
